<template>
  <div class="employees">
    <div class="app-container">
      <el-card>
        <template #header>
          <PageTooles>
            <template #left>
              <span>总计{{ total }}条数据</span>
            </template>
            <template #right>
              <el-button type="primary" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button type="primary" size="small" :loading="downloadLoading" @click="exportData">导出excel</el-button>
              <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
            </template>
          </PageTooles>
        </template>
        <!-- table列表 -->
        <el-table border :data="list" :default-sort="{ prop: 'workNumber', order: 'descending' }">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column>
            <template v-slot="{row}">
              <!-- <el-image class="img" :src="row.staffPhoto" /> -->
              <el-image class="photo" :src="row.staffPhoto" fit="cover" @click="openCode(row.staffPhoto)" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column label="聘用形式">
            <template v-slot="{ row }">
              {{ formOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable prop="correctionTime" label="入职时间" />
          <el-table-column label="账户状态">
            <el-switch v-model="qy" />
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :page-sizes="[10, 5, 2]" background :page-size="query.saze" :current-page="query.page" :total="total" layout="sizes,prev, pager, next" @current-change="changePage" @size-change="changeSize" />
        </el-row>
      </el-card>
    </div>
    <!-- <AddElpmoy :show-dialog="showDialog" @close-dialog="closeDialog" /> -->
    <AddElpmoy :show-dialog.sync="showDialog" @set-dept="getList()" />
    <QrCode ref="qr" :show-code.sync="showCode" />
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import diction from '@/api/constant/employees.js'
import AddElpmoy from './components/add-employee.vue'
import QrCode from './components/qr-code.vue'
export default {
  components: {
    AddElpmoy,
    QrCode
  },
  data () {
    return {
      showCode: false,
      downloadLoading: false,
      showDialog: false,
      qy: true,
      list: [],
      query: {
        page: 1,
        size: 10
      },
      total: 0
    }
  },
  created () {
    this.getList()
  },
  methods: {
    openCode (url) {
      this.showCode = true
      this.$refs.qr.draw(url)
    },
    // 导出
    async exportData () {
      this.downloadLoading = true
      const excel = await import('@/utils/Export2Excel')
      // console.log('胡向南', excel)
      // const header = ['姓名', '性别', '工资']
      // const data = [
      //   ['刘备', '男', 30000],
      //   ['关雨', '男', 30000],
      //   ['张飞', '男', 30000]
      // ]
      const { header, secondArray } = this.provideData()
      excel.export_json_to_excel({
        header,
        data: secondArray,
        filename: `第${this.query.page}页数据`,
        autoWidth: true,
        bookType: 'xlsx'
      })
      this.downloadLoading = false
    },
    provideData () {
      const exportMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(exportMap)
      const filterKeys = Object.values(exportMap)
      const secondArray = []
      this.list.forEach(item => {
        const userInfo = []
        for (const key in item) {
          if (filterKeys.includes(key)) {
            if (key === 'formOfEmployment') {
              userInfo.push(this.formOfEmployment(item[key]))
            } else {
              userInfo.push(item[key])
            }
          }
        }
        secondArray.push(userInfo)
      })
      return { header, secondArray }
    },
    // closeDialog (e) {
    //   this.showDialog = e
    // },
    // 删除
    async delEmployee (row) {
      try {
        await this.$confirm('确定删除？', '提示')
        await delEmployee(row.id)
        const newPage = Math.ceil((this.total - 1) / this.query.size) // 总页数
        if (this.query.page > newPage) {
          // 不正确修复，重新赋值
          this.query.page = newPage
        }
        this.getList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 格式化聘用形式的方法
    formOfEmployment (type) {
      const map = {}
      diction.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 更新列表数据
    async getList () {
      const { rows, total } = await getEmployeeList(this.query)
      // console.log(res)
      this.list = rows
      this.total = total
    },
    changePage (page) {
      this.query.page = page
      this.getList()
    },
    changeSize (size) {
      this.query.size = size
      this.getList()
    }
  }
}
</script>
<style lang="sass" scope>
.photo
  width: 100px
  height: 100px
  border-radius: 100%
</style>
